package com.sc.nft.util;

import cn.hutool.core.date.SystemClock;
import lombok.extern.slf4j.Slf4j;
import java.util.HashSet;
import java.util.Random;

/**
 * @Author zxy
 * @Created 2022年5月29日 23:48:02
 */
@Slf4j
public class ShareCodeUtil {
    /** 自定义进制(0,1没有加入,容易与o,l混淆) */
    private static final char[] r=new char[]{'Q', 'W', 'E', '8', 'A', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P', '5', 'I', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'V', 'Y',  'T', 'N', '6', 'B', 'G', 'H'};

    /** (不能与自定义进制有重复) */
    private static final char b='O';

    /** 进制长度 */
    private static final int binLen=r.length;

    /** 序列最小长度 */
    private static final int s=6;

    /**
     * 根据ID生成六位随机码
     * @param id ID
     * @return 随机码
     */
    public static String toSerialCode(long id) {
        char[] buf=new char[32];
        int charPos=32;

        while((id / binLen) > 0) {
            int ind=(int)(id % binLen);
            buf[--charPos]=r[ind];
            id /= binLen;
        }
        buf[--charPos]=r[(int)(id % binLen)];
        String str=new String(buf, charPos, (32 - charPos));
        // 不够长度的自动随机补全
        if(str.length() < s) {
            StringBuilder sb=new StringBuilder();
            sb.append(b);
            Random rnd=new Random();
            for(int i=1; i < s - str.length(); i++) {
                sb.append(r[rnd.nextInt(binLen)]);
            }
            str+=sb.toString();
        }
        return str;
    }

    public static  HashSet<String> genCDK(int count, int size) {
        HashSet<String> result = new HashSet<>();
        long lastTimestamp =0L;
        for (int i = 0; i < count; i++) {
            long nonce = SystemClock.now();
            if(nonce==lastTimestamp){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    log.error("genCDK error",e);
                }
                nonce = SystemClock.now();
                lastTimestamp = nonce;
            }
            char[] buf=new char[32];
            int charPos=32;

            while((nonce / binLen) > 0) {
                int ind=(int)(nonce % binLen);
                buf[--charPos]=r[ind];
                nonce /= binLen;
            }
            buf[--charPos]=r[(int)(nonce % binLen)];
            String str=new String(buf, charPos, (32 - charPos));
            // 不够长度的自动随机补全
            if(str.length() < size) {
                StringBuilder sb=new StringBuilder();
                sb.append(b);
                Random rnd=new Random();
                for(int j=1; j < size - str.length(); j++) {
                    sb.append(r[rnd.nextInt(binLen)]);
                }
                str+=sb.toString();
            }
            result.add(str);
        }
        return result;
    }


}
